<template>
  <view class="coupon-manager">
    <!-- 新增优惠券按钮 -->
    <view class="add-coupon-section">
      <button class="add-btn" @click="navigateToAdd">+新增</button>
    </view>

    <!-- 标签切换 -->
    <view class="tab-bar">
      <view class="tab-item" :class="{ active: activeTab === 'ongoing' }" @click="switchTab('ongoing')">
        <text class="tab-text">进行中</text>
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'ended' }" @click="switchTab('ended')">
        <text class="tab-text">已结束</text>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <!-- 加载中状态 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-else-if="displayedCoupons.length === 0" class="empty-state">
        <text>暂无优惠券数据</text>
      </view>
      
      <!-- 优惠券列表 -->
      <view v-else v-for="(coupon, index) in displayedCoupons" :key="coupon.id" class="coupon-item">
        <view class="coupon-left">
          <text class="coupon-condition">{{ coupon.condition }}</text>
          <text class="coupon-value">{{ coupon.value }}</text>
        </view>
        <view class="coupon-right">
          <text class="coupon-name">{{ coupon.name }}</text>
          <text class="coupon-date">有效期: {{ coupon.dateRange }}</text>
          <text class="coupon-limit">每人限领{{ coupon.limit }}张</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
// 定义优惠券接口返回的数据类型
interface CouponData {
  id: number;
  name: string;
  type: string;
  discount?: number;
  triggerMoney?: number;
  preferentialMoney?: number;
  start: string;
  end: string;
  num: number;
  size: number;
  expirationStart: string;
  expirationEnd: string;
  status: number;
  createBy: string;
  createTime: string | null;
  updateBy: string;
  updateTime: string | null;
}

// 定义前端使用的优惠券类型
interface Coupon {
  id: number;
  condition: string;
  value: string;
  name: string;
  dateRange: string;
  limit: number;
  status: 'ongoing' | 'ended';
}

// 在 uni-app 中，API 可以通过全局的 uni 对象访问
const navigateTo = uni.navigateTo;
const showToast = uni.showToast;

// 活动标签状态
const activeTab = ref('ongoing');

// 优惠券数据
const coupons = ref<Coupon[]>([]);

// 加载状态
const loading = ref(false);

// 格式化日期函数
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}.${month}.${day}`;
};

// 转换优惠券数据格式
const transformCouponData = (rawData: CouponData[]): Coupon[] => {
  return rawData.map(coupon => {
    let condition = '';
    let value = '';
    
    // 根据类型设置条件和值
    if (coupon.type === '1') { // 满减券
      condition = `满${coupon.triggerMoney}减`;
      value = String(coupon.preferentialMoney);
    } else { // 打折券
      condition = '打折券';
      // 将小数转换为中文折扣描述，如0.8转换为"打八折"
      if (coupon.discount) {
        const discountValue = coupon.discount * 10;
        // 处理整数情况，如8折而不是8.0折
        const discountInteger = Math.floor(discountValue);
        const isInteger = discountValue === discountInteger;
        
        // 数字转中文
        const numToChinese = (num: number): string => {
          const units = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
          return units[num] || '';
        };
        
        if (isInteger) {
          value = `${numToChinese(discountInteger)}折券`;
        } else {
          // 对于非整数折扣，如0.85，显示为"打八五折"
          const integerPart = Math.floor(discountValue);
          const decimalPart = Math.round((discountValue - integerPart) * 10);
          value = `${numToChinese(integerPart)}${numToChinese(decimalPart)}折券`;
        }
      } else {
        value = '折扣信息未设置';
      }
    }
    
    return {
      id: coupon.id,
      condition,
      value,
      name: coupon.name,
      dateRange: `${formatDate(coupon.expirationStart)}-${formatDate(coupon.expirationEnd)}`,
      limit: coupon.size,
      status: coupon.status === 0 ? 'ongoing' : 'ended'
    };
  });
};

// 获取优惠券列表
const fetchCoupons = async () => {
  loading.value = true;
  try {
    showToast({
      title: '加载中...',
      icon: 'loading'
    });
    
    const res = await uni.request({
      url: 'http://localhost:8080/cc/merchant/selectAllCouponList',
      method: 'GET',
      timeout: 10000
    });
    
    if (res.statusCode !== 200) {
      throw new Error(`获取优惠券列表失败: HTTP ${res.statusCode}`);
    }
    
    // 处理响应数据
    const data = res.data as { code?: number; message?: string; data?: CouponData[] } | null;
    
    if (!data || data.code !== 200) {
      throw new Error(`获取优惠券列表失败: ${data?.message || '接口返回错误'}`);
    }
    
    // 转换数据格式并更新状态
    coupons.value = transformCouponData(data.data || []);
    console.log('优惠券列表加载成功:', coupons.value);
    
  } catch (error) {
    console.error('获取优惠券列表失败:', error);
    showToast({
      title: error instanceof Error ? error.message : '加载优惠券失败',
      icon: 'none',
      duration: 3000
    });
  } finally {
    loading.value = false;
    uni.hideLoading();
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCoupons();
});

// 根据激活的标签过滤显示的优惠券
const displayedCoupons = computed(() => {
  return coupons.value.filter(coupon => coupon.status === activeTab.value);
});

// 切换标签
const switchTab = (tab: string) => {
  activeTab.value = tab as 'ongoing' | 'ended';
};

// 跳转到新增优惠券页面
const navigateToAdd = () => {
  navigateTo({
    url: '/pages/coupon/add'
  });
};

// 导入onMounted
import { ref, computed, onMounted } from 'vue';
</script>

<style scoped lang="scss">
.coupon-manager {
  padding: 0 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;

    .title {
      font-size: 36rpx;
      font-weight: bold;
    }

    .header-actions {
      display: flex;
      gap: 20rpx;

      .icon {
        width: 24rpx;
        height: 24rpx;
        background-color: #333;
        border-radius: 50%;
      }
    }
  }

  .add-coupon-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;

    .section-title {
      font-size: 32rpx;
      color: #333;
    }

    .add-btn {
      background-color: #fff;
      border: 1rpx solid #007aff;
      color: #007aff;
      font-size: 28rpx;
      padding: 10rpx 30rpx;
      border-radius: 6rpx;
      width: 180px;
      margin: auto;
    }
  }

  .tab-bar {
    display: flex;
    background-color: #fff;
    border-radius: 10rpx;
    margin: 20rpx 0;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 20rpx 0;
      border-radius: 10rpx;

      .tab-text {
        font-size: 32rpx;
        color: #666;
      }

      &.active {
        background-color: #007aff;

        .tab-text {
          color: #fff;
        }
      }
    }
  }

  .coupon-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    min-height: 300rpx;

    .coupon-item {
      display: flex;
      background-color: #007aff;
      border-radius: 10rpx;
      overflow: hidden;
      padding: 30rpx;

      .coupon-left {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;
        border-right: 1rpx dashed rgba(255, 255, 255, 0.3);

        .coupon-condition {
          font-size: 28rpx;
          margin-bottom: 10rpx;
        }

        .coupon-value {
          font-size: 40rpx;
          font-weight: bold;
        }
      }

      .coupon-right {
        flex: 2;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding-left: 30rpx;
        color: #fff;

        .coupon-name {
          font-size: 32rpx;
          margin-bottom: 10rpx;
        }

        .coupon-date {
          font-size: 26rpx;
          opacity: 0.9;
          margin-bottom: 10rpx;
        }

        .coupon-limit {
          font-size: 26rpx;
          opacity: 0.9;
        }
      }
    }

    .loading, .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 80rpx 0;
      color: #999;
      font-size: 32rpx;
    }
  }
}
</style>